package com.wteam.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wteam.PoJo.DO.user;
import com.wteam.PoJo.DTO.UpUserDTO;
import com.wteam.PoJo.VO.UserVO;
import com.wteam.PoJo.VO.signVO;
import com.wteam.mapper.UserMapper;
import com.wteam.Service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wteam.until.Result;
import com.wteam.until.UserContext;
import com.wteam.until.aliyun.AliOSS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-16
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, user> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOSS aliOSS;

    @Override
    public Result signpoint() {

        // 2.判断当前用户
        Long userId = UserContext.getUser();

        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + userId + now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayofMonth = now.getDayOfMonth();
        //先判断今天是不是已经签到了
        Boolean bit = stringRedisTemplate.opsForValue().getBit(key, dayofMonth - 1);
        if (bit) {
            return Result.error("今天已经签到");
        }
        log.info(userId.toString() + "asfcsdcszxc");
        user nowuser = getById(userId);
        int pints = nowuser.getPoints() + 5;
        stringRedisTemplate.opsForValue().setBit(key, dayofMonth - 1, true);
        lambdaUpdate().set(user::getPoints, pints).eq(user::getPoints, nowuser.getPoints()).update();
        return Result.success("签到成功");
    }

    @Override
    public Result<List<signVO>> selectsign() {

        List<signVO> sign = new ArrayList<>();
        // 2.判断当前用户
        Long userId = UserContext.getUser();
        //拼接key
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + userId + now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //获取本月的全部签到记录
        List<Long> list = stringRedisTemplate.opsForValue().bitField(
                key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands
                                .BitFieldType.unsigned(now.getDayOfMonth()))
                        .valueAt(0));

        if (list == null || list.isEmpty()) {
            return Result.success(sign);
        }
        Long num = list.get(0);
        if (num == 0 || num == null) {
            return Result.success(sign);
        }
//遍历集合做位于运算
        List<signVO> signs = new ArrayList<>();
        for (int i = now.getDayOfMonth(); i > 0; i--) {
            if ((num & 1) == 1) {
                signVO s = new signVO();
                String data = now.format(DateTimeFormatter.ofPattern("yyyyMM")) + "" + i;
                s.setDate(data);
                s.setSignInFlag(true);
                signs.add(s);
            }
            num >>>= 1;
        }
        return Result.success(signs);
    }

    @Override
    public Result<user> selectdetial() {
        Long userid = UserContext.getUser();
log.info("sdcszxczxc");
        //查缓存
        String key = "MyDetial" + "::" + userid;
        UserVO userVO = (UserVO) redisTemplate.opsForValue().get(key);

        if (BeanUtil.isNotEmpty(userVO)) {
            return Result.success(userVO);
        }
        user user = getById(userid);
        UserVO userV = BeanUtil.copyProperties(user, UserVO.class);
        redisTemplate.opsForValue().set(key, userV);
        return Result.success(userV);
    }

    @Override
    public Result updateme(UpUserDTO upUserDTO) throws IOException {
        Long userid = UserContext.getUser();
        String url = null;
        if (upUserDTO.getFile() != null) {
            url = aliOSS.upload(upUserDTO.getFile());
        }
        user user = new user();
        user.setAvatar(url);
        BeanUtil.copyProperties(upUserDTO, user);
        user.setId(userid);
        updateById(user);
        String key = "MyDetial" + "::" + userid;
        redisTemplate.delete(key);
        return Result.success();
    }
}
